package cgroup

import (
	"bufio"
	"log"
	"os"
	"strings"
)

/*
*
[root@k8s-node-demo go-container]# cat /proc/self/mountinfo|grep cgroup
27 20 0:23 / /sys/fs/cgroup ro,nosuid,nodev,noexec shared:4 - tmpfs tmpfs ro,mode=755
28 27 0:24 / /sys/fs/cgroup/systemd rw,nosuid,nodev,noexec,relatime shared:5 - cgroup cgroup rw,xattr,release_agent=/usr/lib/systemd/systemd-cgroups-agent,name=systemd
31 27 0:27 / /sys/fs/cgroup/net_cls,net_prio rw,nosuid,nodev,noexec,relatime shared:6 - cgroup cgroup rw,net_cls,net_prio
32 27 0:28 / /sys/fs/cgroup/hugetlb rw,nosuid,nodev,noexec,relatime shared:7 - cgroup cgroup rw,hugetlb
33 27 0:29 / /sys/fs/cgroup/devices rw,nosuid,nodev,noexec,relatime shared:8 - cgroup cgroup rw,devices
34 27 0:30 / /sys/fs/cgroup/pids rw,nosuid,nodev,noexec,relatime shared:9 - cgroup cgroup rw,pids
35 27 0:31 / /sys/fs/cgroup/perf_event rw,nosuid,nodev,noexec,relatime shared:10 - cgroup cgroup rw,perf_event
36 27 0:32 / /sys/fs/cgroup/freezer rw,nosuid,nodev,noexec,relatime shared:11 - cgroup cgroup rw,freezer
37 27 0:33 / /sys/fs/cgroup/cpuset rw,nosuid,nodev,noexec,relatime shared:12 - cgroup cgroup rw,cpuset
38 27 0:34 / /sys/fs/cgroup/cpu,cpuacct rw,nosuid,nodev,noexec,relatime shared:13 - cgroup cgroup rw,cpu,cpuacct
39 27 0:35 / /sys/fs/cgroup/memory rw,nosuid,nodev,noexec,relatime shared:14 - cgroup cgroup rw,memory
40 27 0:36 / /sys/fs/cgroup/blkio rw,nosuid,nodev,noexec,relatime shared:15 - cgroup cgroup rw,blkio
41 27 0:37 / /sys/fs/cgroup/rdma rw,nosuid,nodev,noexec,relatime shared:16 - cgroup cgroup rw,rdma
*/
func findCgroupPath(subsystem string) (path string) {
	log.Println("subsystem:", subsystem)
	mountInfoFile, err := os.Open("/proc/self/mountinfo")
	if err != nil {
		log.Fatal("找不到/proc/self/mountinfo的存在")
		return ""
	}
	defer mountInfoFile.Close()
	// 逐行读取
	scanner := bufio.NewScanner(mountInfoFile)
	for scanner.Scan() {
		infoList := strings.Split(scanner.Text(), " ") // 输出每一行
		// 37 27 0:33 / /sys/fs/cgroup/cpuset rw,nosuid,nodev,noexec,relatime shared:12 - cgroup cgroup rw,cpuset
		// 38 27 0:34 / /sys/fs/cgroup/cpu,cpuacct rw,nosuid,nodev,noexec,relatime shared:13 - cgroup cgroup rw,cpu,cpuacct
		// 最后一个元素按照逗号分割，遍历只要能找到，就意味着存在目标子系统
		subsystemList := strings.Split(infoList[len(infoList)-1], ",")
		for _, item := range subsystemList {
			if item == subsystem {
				return infoList[4] // 响应 /sys/fs/cgroup/cpuset
			}
		}
	}

	if err := scanner.Err(); err != nil {
		log.Fatalf("reading standard input: %v\n", err)
		return ""
	}

	return ""
}
